package frobagroup.utils.fileUtils.impl;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import frobagroup.utils.Constants;
import frobagroup.utils.fileUtils.FileUploadServer;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Tinsley on 2016/7/29.
 */

@Service
public class FileUploadServerImpl implements FileUploadServer {


    public static final String FILE_URL = "https://doc.csssrv.com/get/";
    public static final String FILE_GET_API = "api/document/get/";

    private static final Logger logger = LoggerFactory.getLogger(FileUploadServerImpl.class);

    private static final String DATE_PATTERN = "yyyy-MM-dd-hhmmssSSS";
    private static final String FOLDER_PATTERN = "yyyy-MM";

    private static final String ACCESS_KEY_ID = "K0ZM1gQQrhgzhknX";
    private static final String ALIYUN_BUCKETNAME = "ciie-file-service";
    private static final String ACCESS_KEY_SECRET = "HmLRQutu5PlAQvTQm3n8iZA12UNdxL";

//    private static final String PROTECTED_AWS_BUCKETNAME = "ciie-file-service";
    private static final String PROTECTED_AWS_BUCKETNAME = "plumtree-files";
//    private static final String PUBLIC_AWS_BUCKETNAME = "ciie-file-public";  //plumtree-files
    private static final String PUBLIC_AWS_BUCKETNAME = "plumtree-files";  //plumtree-files
    //for us
    private static final String AWS_ACCESS_KEY_US = "AKIAJLZEZ7FGXDGMYGDQ";
    private static final String AWS_SECRET_KEY_US = "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";
    private static final Regions AMAZON_REGIONS_US = Regions.AP_SOUTHEAST_1;//新加坡
    //for cn
    private static final String AWS_ACCESS_KEY_CN = "AKIAOSOHWGODP2UXU5LA";
    private static final String AWS_SECRET_KEY_CN = "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";
    private static final Regions AMAZON_REGIONS_CN = Regions.AP_SOUTHEAST_1;

    private static final String PROTECTED_FILE_URL_CN = "https://file.ciiedu.cn/get/";
    private static final String PROTECTED_FILE_URL_US = "https://file.ciiedu.net/get/";

//    private static final String PUBLIC_FILE_URL_CN = "https://s3.cn-north-1.amazonaws.com.cn/" + PUBLIC_AWS_BUCKETNAME + "/";
    private static final String PUBLIC_FILE_URL_CN = "https://s3-ap-southeast-1.amazonaws.com/" + PUBLIC_AWS_BUCKETNAME + "/";
//    private static final String PUBLIC_FILE_URL_US = "https://s3.amazonaws.com/" + PUBLIC_AWS_BUCKETNAME + "/";
    private static final String PUBLIC_FILE_URL_US = "https://s3-ap-southeast-1.amazonaws.com/" + PUBLIC_AWS_BUCKETNAME + "/";


    private static String formatFileName(String originalName) {

        DateFormat format = new SimpleDateFormat(DATE_PATTERN);
        String date = format.format(new Date());
        int lastIndex = originalName.lastIndexOf(".");
        if(lastIndex == -1){
            return originalName + date;
        }else {
            return originalName.substring(0, lastIndex) + date + originalName.substring(lastIndex);
        }
    }

    private static String formatFolderNameByDate() {
        DateFormat format = new SimpleDateFormat(FOLDER_PATTERN);
        return "EDU_" + format.format(new Date());
    }

    @Override
    public String uploadFileToCloud(MultipartFile file) throws Exception {
        return uploadFileToALY(file);
    }

    @Override
    public boolean deletePublicFile(String key) throws Exception {
        try {
            new OSSClient(Constants.END_POINT, Constants.ACCESS_KEY_ID,
                    Constants.ACCESS_KEY_SECRET).deleteObject(Constants.BUCKET_NAME,key);
        }catch (Exception e){
            logger.warn("Delete ["+ key +"] from CN ALY failed.", e);
        }
        return Boolean.TRUE;
    }

    private String uploadFileToALY(MultipartFile file) throws Exception {
        InputStream in = null;
        try {

            in = file.getInputStream();
            String fileName = formatFileName(file.getOriginalFilename());
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            objectMetadata.setContentType(file.getContentType());
            OSSClient ossClient = new OSSClient(Constants.END_POINT, Constants.ACCESS_KEY_ID,
                    Constants.ACCESS_KEY_SECRET);
            ossClient.putObject(Constants.BUCKET_NAME,Constants.FOLDER_NAME+"/" + fileName,in,objectMetadata);
            return Constants.FOLDER_NAME+"/" + URLEncoder.encode(fileName, "UTF-8");

        } finally {
            IOUtils.closeQuietly(in);
        }
    }


    private AmazonS3Client getAmazonS3Client() {
//        if(properties.isServerLocationInChina()) {
//            return getAmazonS3ClientFromCN();
//        }else{
//            return getAmazonS3ClientFromUS();
//        }
        return getAmazonS3ClientFromUS();
    }

//    private String getProtectedHostUrl(){
//        if(properties.isServerLocationInChina()) {
//            return PROTECTED_FILE_URL_CN;
//        }else{
//            return PROTECTED_FILE_URL_US;
//        }
//    }

//    private String getPublicHostUrl(){
//        if(properties.isServerLocationInChina()) {
//            return PUBLIC_FILE_URL_CN;
//        }else{
//            return PUBLIC_FILE_URL_US;
//        }
//    }

    private AmazonS3Client getAmazonS3ClientFromCN() {
        AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(AWS_ACCESS_KEY_CN, AWS_SECRET_KEY_CN), new ClientConfiguration());
        s3Client.setRegion(Region.getRegion(AMAZON_REGIONS_CN));
        return s3Client;
    }

    private AmazonS3Client getAmazonS3ClientFromUS() {
        AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(AWS_ACCESS_KEY_US, AWS_SECRET_KEY_US), new ClientConfiguration());
        s3Client.setRegion(Region.getRegion(AMAZON_REGIONS_US));
        return s3Client;
    }



}
